﻿using BLL;

using Model;

using NCRE学生考试端V1._0.PPT操作题类;

//using NCRE学生考试端V1._0.Word操作题类;

using System;

using System.ComponentModel;

using System.Data;

using System.Windows.Forms;

using System.Diagnostics;

using System.Threading;

using System.Text.RegularExpressions;

using System.IO;

using System.Data.SqlClient;

using DLL;

using DAL;



namespace NCRE学生考试端V1._0.教师端操作类.SecondJudge

{

    /// <summary>

    /// 教师端二次判分   

    /// 时间：2020-12-01

    /// 作者：张有博

    /// </summary>

    public partial class frmSecondJudge : Form

    {



        private static int SelectNum = 0;

        private static int WordNum = 0;

        private static int PptNum = 0;

        private static int WinNum = 0;

        private static int ExcelNum = 0;

        private static int IENum = 0;

        /// <summary>

        /// 用于进度条

        /// </summary>

        BackgroundWorker worker;

        /// <summary>

        /// 错误日志

        /// </summary>

        private LogEntity logInfo = new LogEntity();





        public frmSecondJudge()

        {

            InitializeComponent();



            //worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);



        }



        #region 异步判分

        /// <summary> 

        /// 异步判分

        /// </summary> 

        /// <param name="sender"></param> 

        /// <param name="e"></param> 

        private void worker_DoWork(object sender, DoWorkEventArgs e)

        {

            try

            {

                //用于计算执行的操作             

                Kill();



                string TimeTamp = MyInfo.TimeTamp();

                string studentID = MyInfo.MystudentID();

                #region 初始化logInfo属性 2018年3月31日

                logInfo.timeSpan = TimeTamp;

                logInfo.studentId = studentID;

                logInfo.pagerType = MyInfo.MyPaperType();

                logInfo.errerInfo = string.Empty;

                logInfo.excelInfo = string.Empty;

                logInfo.ieInfo = string.Empty;

                logInfo.pptInfo = string.Empty;

                logInfo.sumErrerInfo = string.Empty;

                logInfo.uploadInfo = string.Empty;

                logInfo.wordInfo = string.Empty;

                logInfo.winInfo = string.Empty;

                logInfo.userIp = MyInfo.GetInternalIP();

                #endregion



                #region 进行评分操作 2015年12月14日13:52:43-李少然-卢彦聪改为多线程判分-2018-5-1



                #region 多线程异步判分

                Thread wordthread = new Thread(WordThread);  //new一个线程执行具体的方法

                wordthread.Start(); //执行线程



                Thread winthread = new Thread(WinThread);

                winthread.Start();



                Thread excelthread = new Thread(ExcelThread);

                excelthread.Start();



                Thread pptthread = new Thread(PptThread);

                pptthread.Start();



                Thread iethread = new Thread(IEThread);

                iethread.Start();



                Thread selectthread = new Thread(SelectThread);

                selectthread.Start();



                //阻塞调用线程，直到某个线程终止时为止

                wordthread.Join();

                winthread.Join();

                excelthread.Join();

                pptthread.Join();

                iethread.Join();

                selectthread.Join();

                #endregion



                #region 线程终止

                if (WordNum == 0)

                {

                    wordthread.Abort();

                }

                if (WinNum == 0)

                {

                    winthread.Abort();

                }

                if (ExcelNum == 0)

                {

                    excelthread.Abort();

                }

                if (PptNum == 0)

                {

                    pptthread.Abort();

                }

                if (IENum == 0)

                {

                    iethread.Abort();

                }

                if (SelectNum == 0)

                {

                    selectthread.Abort();

                }

                #endregion



                Kill();



                #region 分数汇总 修改人：白爱民-修改分数汇总条件-2018年12月23日

                //查询绑定表中的考试模式

                StudentBindPaperTypeBLL studentBindPaperBll = new StudentBindPaperTypeBLL();

                DataTable dt = studentBindPaperBll.SelectByStudentID(studentID);

                string ExamModel = dt.Rows[0]["ExamModel"].ToString();









                try

                {

                    //如果上边的excel等判分完成了，就进行分数的汇总                    

                    //if ((WordNum + WinNum + ExcelNum + PptNum + IENum + SelectNum) ==6)

                    //{

                    //    //计算一个学生一套试卷的总分-李芬-2015年11月30日

                    //    TypeSumFrationBll typesumfration = new TypeSumFrationBll();

                    //    typesumfration.SumFration(studentID, TimeTamp, ExamModel);

                    //}



                    if ((WordNum + WinNum + ExcelNum + PptNum + IENum + SelectNum) > 0)

                    {

                        //计算一个学生一套试卷的总分-李芬-2015年11月30日

                        TypeSumFrationBll typesumfration = new TypeSumFrationBll();

                        typesumfration.SumFration(studentID, TimeTamp, ExamModel);







                    }

                }

                catch (Exception em)

                {

                    //MessageBox.Show("分数汇总错误")

                    logInfo.sumErrerInfo += "分数汇总错误" + em.Message;

                }

                #endregion



                #endregion

            }

            catch (Exception eme)

            {

                logInfo.errerInfo = "交卷失败" + eme.Message;

                CheckForIllegalCrossThreadCalls = false;



                Environment.Exit(0);

            }



            //考试模式下不更新到数据库——薛帅行——2018年12月29号15点10分

            DataTable dt3 = new LogBll().QuerySetUpBll();

            if (dt3.Rows[0]["is_upload"].ToString() != "0")   //根据是否有提示框来判断，因为is_exam没有地方修改过，一直为1  //练习模式

            {

                #region 将考生数据存到数据库中——薛帅行——2018年12月25号16点49分



                //float sumFration = float.Parse(Excelsumfration) + float.Parse(IEsumfration) + float.Parse(pptsumfration) + float.Parse(selectsumfration) + float.Parse(winsumfration) + float.Parse(wordsumfration);

                ScoreEntity score1 = new ScoreEntity();

                score1.studentID = FrmLogin.studentID;

                TypeSumFrationBll typesumfration1 = new TypeSumFrationBll();

                DataTable dt1 = typesumfration1.inquiryScore(score1);



                ScoreAdornEntity score = new ScoreAdornEntity();

                score.userId = LoginEntity.studentID;

                score.userName = LoginEntity.studentName;

                score.userCode = FrmLogin.studentID;   //学号登陆怎么判断

                score.totalScore = Convert.ToSingle(dt1.Rows[0]["score"]);

                score.multipleChoeceRanking = Convert.ToString(dt1.Rows[0]["SelectScore"]);

                score.WordRanking = Convert.ToString(dt1.Rows[0]["WordScore"]);

                score.ExcelRanking = Convert.ToString(dt1.Rows[0]["ExcelScore"]);

                score.IERanking = Convert.ToString(dt1.Rows[0]["IEScore"]);

                score.WindowsRanking = Convert.ToString(dt1.Rows[0]["WinScore"]);

                score.PPTRanking = Convert.ToString(dt1.Rows[0]["PPTScore"]);

                score.loginTime = Convert.ToDateTime(dt1.Rows[0]["timeSpan"]);

                score.is_Input = "1";



                TypeSumFrationBll addScoreAdorn = new TypeSumFrationBll();

                addScoreAdorn.addScoreAdorn(score);

                #endregion

            }

        }

        #endregion



        #region 多线程需要执行的各个方法

        private void SelectThread()

        {

            TypeSumFrationBll typesumfration = new TypeSumFrationBll();

            string TimeTamp = MyInfo.TimeTamp();

            string studentID = MyInfo.MystudentID();

            //计算选择题型的总分—李芬-2015年11月30日

            typesumfration.SelectsumFration(studentID, TimeTamp);

            SelectNum = 1;

        }



        private void WordThread()

        {

            #region Word判分  2015年11月23日

            try

            {

                TypeSumFrationBll typesumfration = new TypeSumFrationBll();

                string TimeTamp = MyInfo.TimeTamp();

                string studentID = MyInfo.MystudentID();



                //TODO:word判分

                WordQuestionRecordEntity student = new WordQuestionRecordEntity();

                WordQuestionEntityBll wordquestionbll = new WordQuestionEntityBll();

                WordQuestionEntity wordinfo = new WordQuestionEntity();





                //根据试卷类型查找题库中的题，然后对这些题根据flag进行判分

                string PaperType;

                PaperType = MyInfo.MyPaperType();

                //下面的dt表示按照试卷类型在数据库中加载word的题目信息

                DataTable dt = wordquestionbll.LoadWordByPaperType(PaperType);

                //得到学生答题的学生号

                student.StudentID = MyInfo.MystudentID();







                //以上修改



                //word判分      

                JudgeWord(PaperType, student, wordquestionbll, wordinfo, dt);

                //计算word总分                        

                typesumfration.WordSumFration(studentID, TimeTamp);

                WordNum = 1;

            }

            catch (Exception em)

            {

                logInfo.wordInfo = "word判分: " + em.Message;

            }

            #endregion

        }



        private void PptThread()

        {

            #region ppt判分

            try

            {

                TypeSumFrationBll typesumfration = new TypeSumFrationBll();

                string TimeTamp = MyInfo.TimeTamp();

                string studentID = MyInfo.MystudentID();

                PptJudgeHelper Pptjudge = new PptJudgeHelper();

                Pptjudge.PptJudgebyQuestionFlag();

                //计算PPT题型总分-王荣晓-2015年11月30日

                typesumfration.PPTSumFration(studentID, TimeTamp);

                PptNum = 1;

            }

            catch (Exception em)

            {

                logInfo.pptInfo = "ppt错误：" + em.Message;

            }

            #endregion

        }



        private void WinThread()

        {

            #region Windows判分 2015年11月23日



            try

            {

                TypeSumFrationBll typesumfration = new TypeSumFrationBll();

                string TimeTamp = MyInfo.TimeTamp();

                string studentID = MyInfo.MystudentID();

                WinQuestionEntity wininfo = new WinQuestionEntity();

                wininfo.paperType = MyInfo.MyPaperType();



                WindowsQuestionFlag windowsQuestionFlag = new WindowsQuestionFlag();

                windowsQuestionFlag.SwitchQuestionFlag(wininfo);

                WinQuestionEntityBll winquestion = new WinQuestionEntityBll();

                WinQuestionRecordEntity winrecored = new WinQuestionRecordEntity();

                winrecored.studentID = MyInfo.MystudentID();



                //启动一个新线程，用于windows判分

                winquestion.ReturnScore(WindowsLoadInfo.list, winrecored);



                //计算windows题型总分-王荣晓-2015年11月30日

                typesumfration.windowsSumFration(studentID, TimeTamp);

                WinNum = 1;

            }

            catch (Exception em)

            {

                //MessageBox.Show("windows错误")

                logInfo.winInfo = "windows错误" + em.Message;

            }

            #endregion

        }



        private void IEThread()

        {

            #region IE判分 2015年11月23日



            try

            {

                TypeSumFrationBll typesumfration = new TypeSumFrationBll();

                string TimeTamp = MyInfo.TimeTamp();

                string studentID = MyInfo.MystudentID();

                //txtMsg.Text += "\r\nIE开始判分...."

                IEQuestionEntity ieinfo = new IEQuestionEntity();

                ieinfo.paperType = MyInfo.MyPaperType();

                IEQuestionFlag iequestionflag = new IEQuestionFlag();

                iequestionflag.SwitchQuestionFlag(ieinfo);

                IeQuestionEntityBll question = new IeQuestionEntityBll();

                IEQuestionRecordEntity ierecored = new IEQuestionRecordEntity();

                ierecored.studentID = MyInfo.MystudentID();



                question.ReturnScore(IELoadInfo.list, ierecored);

                //计算PPT题型总分-王荣晓-2015年11月30日

                typesumfration.IESumFration(studentID, TimeTamp);

                //txtMsg.Text += "\r\nIE判分成功！"

                IENum = 1;

            }

            catch (Exception em)

            {

                logInfo.ieInfo = "ie错误" + em.Message;

            }

            #endregion

        }



        private void ExcelThread()

        {

            #region Excel判分 2015年11月23日

            try

            {

                TypeSumFrationBll typesumfration = new TypeSumFrationBll();

                string TimeTamp = MyInfo.TimeTamp();

                string studentID = MyInfo.MystudentID();

                //txtMsg.Text += "\r\nExcel开始判分......"

                ExcelQuestionEntity excelinfo = new ExcelQuestionEntity();

                ExcelJudgeHelper excelhelper = new ExcelJudgeHelper();

                ExcelQuestionRecordEntity excelrecored = new ExcelQuestionRecordEntity();

                ExcelEntityBll Excelquestionbll = new ExcelEntityBll();



                excelhelper.SelectJudge(excelinfo);

                excelrecored.StudentID = MyInfo.MystudentID();

                Thread.Sleep(200);

                Excelquestionbll.ReturnExcelScore(ExcelLoading.list, excelrecored);

                //计算Excel题型总分-王荣晓-2015年11月30日

                typesumfration.ExcelSumFration(studentID, TimeTamp);

                ExcelNum = 1;

            }

            catch (Exception em)

            {

                //MessageBox.Show("excel错误")

                logInfo.excelInfo = "excel错误" + em.Message;

            }



            #endregion

        }

        #endregion



        #region Kill()-杀掉所有进程

        /// <summary>

        /// 杀掉所有进程

        /// </summary>

        public void Kill()

        {

            //杀txt

            foreach (Process txt in Process.GetProcessesByName("notepad"))

            {

                txt.Kill();

            }

            //杀Word

            foreach (Process word in Process.GetProcessesByName("WINWORD"))

            {

                word.Kill();

            }

            //杀Excel

            foreach (Process excel in Process.GetProcessesByName("EXCEL"))

            {

                excel.Kill();

            }



            //杀图片

            foreach (Process acdsee5 in Process.GetProcessesByName("ACDSee5"))

            {

                acdsee5.Kill();

            }



            //杀PPT

            foreach (Process ppt in Process.GetProcessesByName("POWERPNT"))

            {

                ppt.Kill();

            }

            //杀图片

            foreach (Process dllhost in Process.GetProcessesByName("dllhost"))

            {

                dllhost.Kill();

            }

            //杀图片

            foreach (Process mspaint in Process.GetProcessesByName("mspaint"))

            {

                mspaint.Kill();

            }

            //杀图片

            foreach (Process Photoshop in Process.GetProcessesByName("Photoshop"))

            {

                Photoshop.Kill();

            }

            //杀图片

            foreach (Process OIS in Process.GetProcessesByName("OIS"))

            {

                OIS.Kill();

            }

            //杀IE

            foreach (Process iexplore in Process.GetProcessesByName("iexplore"))

            {

                iexplore.Kill();

            }

        }

        #endregion





        #region 判断考试模式 修改人：李金颖-添加备注-2018-12-21 10:49:40

        /// <summary> 

        /// 异步完成-学生端系统设置部署

        /// </summary> 

        ///// <param name="sender"></param> 

        ///// <param name="e"></param> 

        //private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)

        //{

        //    DataTable dt = new LogBll().QuerySetUpBll();

        //    //上传考生文件——“0”上传

        //    if (dt.Rows[0]["is_upload"].ToString() == "0" && !UploadFile())

        //    {

        //        UpdateIsUse(2);//上传失败IsUse改成2

        //    }

        //    else

        //    {

        //        UpdateIsUse(0);//交卷IsUse改成0

        //    }

        //    //显示成绩——"1'为显示成绩，“0”为不显示

        //    if (dt.Rows[0]["is_showScore"].ToString() == "1")

        //    {

        //        ShowScore();

        //    }

        //    //锁屏——"0"为锁屏

        //    if (dt.Rows[0]["is_lockScreen"].ToString() == "0")

        //    {

        //        frmWaitLock frmLock = new frmWaitLock();

        //        frmLock.Show();

        //        Close();

        //        return;

        //    }

        //    Application.Exit();

        //}

        #endregion



        #region 更改用户是否登录过的标志

        /// <summary>

        /// 更改用户是否登录过的标志

        /// </summary>

        /// <param name="IsUse">要修改的IsUse</param>

        void UpdateIsUse(int IsUse)

        {

            //StudentBindType 的IsUse属性，0未在线,1在线,2上传失败

            StudentBindPaperTypeEntity studentBin = new StudentBindPaperTypeEntity();

            studentBin.TimeTamp = MyInfo.TimeTamp();

            studentBin.StudentID = MyInfo.MystudentID();

            studentBin.IsUse = IsUse;

            StudentBindTypeEntityBll studentbll = new StudentBindTypeEntityBll();

            studentbll.UpdateStudentByIsUse(studentBin);

        }

        #endregion





        #region Word题型判分逻辑 -2020年12月1日 修改人：张有博

        /// <summary>

        /// word判分

        /// </summary>

        /// <param name="paperType"></param>

        /// <param name="student"></param>

        /// <param name="wordquestionbll"></param>

        /// <param name="wordinfo"></param>

        /// <param name="dt"></param>

        private void JudgeWord(string paperType, WordQuestionRecordEntity student, WordQuestionEntityBll wordquestionbll, WordQuestionEntity wordinfo, DataTable dt)

        {

            //判断表格C是否存在

            //需要修改--传参

            string filePath = string.Format("D:\\" + MyInfo.MystudentID() + "\\计算机一级考生文件\\" + paperType + "卷\\Wordkt\\bg" + paperType + ".docx");

            string fileword = string.Format("D:\\" + MyInfo.MystudentID() + "\\计算机一级考生文件\\" + paperType + "卷\\Wordkt\\Word" + paperType + ".docx");





            WordAQuestionFlag WordFlag = null;

            WordFlag = new WordAQuestionFlag();



            if (MyInfo.exitsDoc(fileword))            // 判断此路径下是否有word文件

            {

                WordFlag.SwitchQuestionFlag(wordinfo, dt);//判分

            }

            else if (MyInfo.exitsDoc(filePath))            // 判断此路径下是否有文件

            {

                WordFlag.SwitchQuestionFlag(wordinfo, dt);

            }

            else

            {

                for (int i = 0; i < dt.Rows.Count; i++)

                {

                    WordQuestionRecordEntity Student = new WordQuestionRecordEntity();

                    Student.StudentID = FrmLogin.studentID;

                    Student.PaperType = MyInfo.MyPaperType();

                    Student.TimeStamp = MyInfo.TimeTamp();

                    Student.QuestionID = Convert.ToDouble(dt.Rows[i]["QuestionID"]);

                    Student.ExamAnswer = "本地无考生文件";

                    Student.Fration = "0";

                    WordLoadinfo.list.Add(Student);

                }



            }



            wordquestionbll.ReturnScore(WordLoadinfo.list, student);

        }

        #endregion



























        private void frmSecondJudge_Load(object sender, EventArgs e)

        {



        }







        private void btnSecondJudge_Click(object sender, EventArgs e)

        {

            string TimeTamp;  //声明时间

            //拿数据  遍历

            string folderFullName = "D:\\15028002462\\计算机一级考生文件";

            DirectoryInfo TheFolder = new DirectoryInfo(folderFullName);

            //遍历文件夹

            foreach (DirectoryInfo NextFolder in TheFolder.GetDirectories())

            {

                string studentID = NextFolder.Name;//拿到考号

                //遍历文件

                foreach (FileInfo NextFile in TheFolder.GetFiles())

                {

                    string paperType = NextFile.Name;//拿到试卷类型

                    FrmLogin.studentID = studentID;

                    TimeTamp = MyInfo.TimeTamp(); //时间

                    if (TimeTamp == "")//交卷未成功！

                    {

                        InsertStudentByIsUseStudentID(studentID, paperType); //插入时间

                    }

                    worker = new BackgroundWorker();

                    worker.DoWork += new DoWorkEventHandler(worker_DoWork);

                }

            }

        }



        public int InsertStudentByIsUseStudentID(string studentId, string paperType)

        {

            SQLHelper sqlHelper = new SQLHelper();

            string sql = "insert into StudentBindPaperTypeEntity(StudentID,PaperType,IsUse,CollegeID,TimeTamp,IP,ExamModel)value(@studentID,@PaperType,@isuse,@CollegeID,@TimeTamp,@IP,@ExamModel);";

            SqlParameter[] paras = new SqlParameter[]{

                new  SqlParameter("@studentID",studentId),

                new SqlParameter("@PaperType",paperType),

                new SqlParameter ("@isuse",1 ),

                new SqlParameter("@CollegeID",00),

                new SqlParameter("@TimeTamp",DateTime.Now),

                new SqlParameter("@IP","000.000.000.00"),

                new SqlParameter("@ExamModel","考试模式")



            };

            int i = sqlHelper.ExecuteNonQuery(sql, paras, CommandType.Text);

            return i;

        }



    }

}

